package com.yq.interview.study.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @ClassName Spinlock
 * @Description 自旋锁的代码实现
 * @Author yaoqiang
 * @Date 2020/11/19 11:53
 * @Version 1.0
 */
public class SpinlockDemo {
    public static void main(String[] args) {
        SpinlockDemo spinlockDemo=new SpinlockDemo();
        new Thread(()->{
            spinlockDemo.myLock();
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            spinlockDemo.myUnlock();
        },"t1").start();
        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }

        new Thread(()->{
            spinlockDemo.myLock();
            spinlockDemo.myUnlock();
        },"t2").start();


/*        AtomicInteger atomicInteger=new AtomicInteger();
        atomicInteger.getAndIncrement();//采用的自旋锁
        public final int getAndAddInt(Object var1, long var2, int var4) {
            int var5;
            do {
                var5 = this.getIntVolatile(var1, var2);
            } while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));

            return var5;
        }*/
//原子引用线程
    }

    //原子引用线程
    AtomicReference<Thread> atomicReference=new AtomicReference<>();

    public void myLock(){
        Thread thread=Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+"  myLock");
        while (!atomicReference.compareAndSet(null,thread)){
        }
    }

    public void myUnlock(){
        Thread thread=Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+"+++++myUnlock()");
        atomicReference.compareAndSet(thread,null);
    }

}
